
#include "key_enc.h"
#include "bsp_iflash.h"

typedef struct {
    uint8_t len;
    char data[32];
    uint8_t crc;
}enc_key_t;

/**
 * @brief 获取设备密钥
 * @param  key              My Param doc
 * @param  len              My Param doc
 * @return int32_t 
 */
int32_t qltask_modem_fw_encryption_key_get(char *key, size_t len)
{
    #define ENC_KEY_OFFSET (32 * 1024 + 0x23) // BOOT 32K
    // char *key_array = {"55c808d87dc06bb5d4675fca4bc0ce3c"};       
    enc_key_t enc;             
                     
    bsp_iflash_read((uint32_t)(BANK_1_ADDR + ENC_KEY_OFFSET), &enc, sizeof(enc_key_t));

    strncpy(key, enc.data, len);

    return len;
}

/**
 * @brief 设置设备密钥
 * @param  key              My Param doc
 * @param  len              My Param doc
 * @return int32_t 
 */
int32_t qltask_modem_fw_encryption_key_set(char *key, size_t len)
{
    #define ENC_KEY_OFFSET (32 * 1024 + 0x23) // BOOT 32K

    enc_key_t enc = {0};      

    enc.len = len & 0xFF;
    strcpy(enc.data, key);
    for(uint8_t i = 0; i < len; i++) {
        enc.crc += key[i];
    }

    bsp_iflash_write_random((uint32_t)(BANK_1_ADDR + ENC_KEY_OFFSET), &enc, sizeof(enc));

    return len;
}

